package com.example.backend.service;

import com.example.backend.mapper.Store.ChatMessagesRepository;
import com.example.backend.pojo.ChatMessages;
import com.example.backend.pojo.DTO.ChatMessageDTO;
import com.example.backend.pojo.DTO.ChatSessionDTO;
import com.example.backend.pojo.DTO.UserChatSessionSummaryDTO;
import com.example.backend.util.ThreadLocalUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChatMessagesService {
    @Autowired
    private ChatMessagesRepository chatMessagesRepository;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    public List<UserChatSessionSummaryDTO> findAllByUserId() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        List<ChatMessages> chatMessages = chatMessagesRepository.findAllByUserId(id);//获取用户的所有聊天记录

        // 按 memoryId 分组并提取最新日期
        return chatMessages.stream()
                .collect(Collectors.groupingBy(
                        ChatMessages::getMemoryId,
                        Collectors.maxBy(Comparator.comparing(msg -> msg.getMessageId().getDate()))
                ))
                .entrySet().stream()
                .map(entry -> {
                    String memoryId = entry.getKey();
                    Date latestDate = entry.getValue().get().getMessageId().getDate();
                    String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(latestDate);
                    return new UserChatSessionSummaryDTO(memoryId, formattedDate);
                })
                .toList();
    }

    // 查询特定 memoryId 的所有记录
    public ChatSessionDTO findAllByMemoryId(String memoryId) {
        List<ChatMessages> chatMessages = chatMessagesRepository.findAllByMemoryId(memoryId);
        List<ChatMessageDTO> messageDTOs = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (ChatMessages msg : chatMessages) {
            try {
                List<Map<String, Object>> messages = objectMapper.readValue(
                        msg.getContent(),
                        objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class)
                );

                for (Map<String, Object> content : messages) {
                    String type = (String) content.get("type");
                    if ("USER".equals(type) || "AI".equals(type)) {
                        String messageContent;
                        if ("USER".equals(type)) {
                            List<Map<String, Object>> contents = (List<Map<String, Object>>) content.get("contents");
                            messageContent = (contents != null && !contents.isEmpty())
                                    ? (String) contents.get(0).get("text")
                                    : "";
                        } else {
                            messageContent = (String) content.get("text");
                        }
                        messageDTOs.add(new ChatMessageDTO(type, messageContent));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String sessionDate = chatMessages.isEmpty()
                ? dateFormat.format(new Date())
                : dateFormat.format(chatMessages.get(chatMessages.size() - 1).getMessageId().getDate());

        return new ChatSessionDTO(
                memoryId.toString(),
                sessionDate,
                messageDTOs
        );
    }

}